$(function() {
    $lang.init();
    $page.init();
    $product.init();
});
var $product = {
    fields: {
        name: 'product_name',
        order: 'product_order',
        level: "product_level",
        language: 'product_language',
        status: 'status',
        featured: 'featured',
        summary: 'product_summary',
        description: 'product_description_slave',
        meta_title: 'product_meta_title',
        meta_keyword: 'product_meta_keyword',
        meta_description: 'product_meta_description',
        meta_robot: 'product_meta_robot',
        image: 'product_image',
        source: 'product_source'
    },
    init: function() {
        this._initDialog()
                ._initEvent()
                ._initCategoryList();

        this.renderDescriptionField()
                .uploadImage();
    },
    _initSearch: function() {
        $('#search_name, #search_category, \n\
                #search_order_from, #search_order_to,\n\
                #search_date_from, #search_date_to,\n\
                #search_id_from, #search_id_to').keyup(function() {
            $product.refresh();
        });

        $('#search_is_actived, #search_featured, #search_language').change(function() {
            $product.refresh();
        });

        return this;
    },
    _initSort: function() {
        $('.sort').click(function($event) {
            var $column = $(this).attr('id').toString().replace('sort_', '');
            var $object = $(this);
            var $option = {
                type: 'post',
                url: $tut.siteUrl('product/admincp/index/sort'),
                dataType: 'json',
                data: {column: $column},
                success: function($response, $status) {
                    if ($response.result) {
                        //Change arrow of column.
                        $product.resetSort();
                        if (!$response.data.type_sort) {
                            $('#sort_order').parent().addClass('sortdesc');
                        }
                        else {
                            $object.parent().addClass('sort' + $response.data.type_sort);
                        }
                        //Get current page....
                        var $curPage = $('#current_page_product').text();
                        $curPage = !$curPage ? 1 : $curPage;
                        $product.getList($curPage);
                    }
                }
            };

            $tut.ajax($option);
        });

        return this;
    },
    _initDialog: function() {
        //Initialzie datepicker for search.
        $('input.date').datepicker({
            onSelect: function($date) {
                $product.refresh();
            },
            dateFormat: 'yy-mm-dd'
        });

        //Dialog add product...
        $('#dialog_add').dialog({
            autoOpen: false,
            height: 600,
            width: 800,
            modal: true,
            resizable: false,
            draggable: true,
            buttons: {
                Save: function() {
                    $product.add();
                },
                Reset: function() {
                    $product.resetFormAdd();
                },
                Cancel: function() {
                    $product.resetFormAdd();
                    $(this).dialog("close");
                }
            },
            close: function() {
            }
        });
        //Vertical tabs.
        $("#dialog_add").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
        $("#dialog_add li").removeClass("ui-corner-top").addClass("ui-corner-left");

        return this;
    },
    _initCategoryList: function() {
        //product category tree view
        $("#product_category_tree").treeview();

        return this;
    },
    _initEvent: function() {
        //Initialize dialog upload image when add new product.
        $('input#product_image_btn').click(function() {
            $dialog.container({
                title: 'Image',
                body: $project.removeComment($('#upload_image').html()),
                id: 'dlg_upload_img',
                buttons: {
                    Upload: function() {
                        $product.uploadImage();
                        $('#form_image_product').submit();
                        $dialog.close().destroy();
                    },
                    Cancel: function() {
                        $dialog.close();
                        $product.resetUploadImgInput();
                        $dialog.destroy();
                    }
                }
            });
        });
        $('input.add').click(function() {
            //Reset form add to become add action
            $('#form_add').attr('action', $tut.siteUrl('product/admincp/index/add'));
            //Reset dialog title to add product.
            $('#dialog_add')
                    .dialog('option', 'title', $lang.phrases.add_product)
                    .dialog("open");
        });

        //Check all product...
        $('input#all_product').click(function() {
            $('.product-select').prop('checked', this.checked);
        });

        //Delete multiple product...
        $('input#delete_product').click(function() {
            $product.resetDeletedItems()
                    .showDeletedItems();
        });

        //Edit a product
        $('.edit-product').live('click', function($event) {
            $event.preventDefault();
            var $id = $(this).prop('id')
                    .toString()
                    .replace('edit_product_', '');

            $product.getById($id);
        });

        //Intialize search and sort event.
        this._initSearch()
                ._initSort();

        return this;
    },
    refresh: function() {
        $page.get(0);
    },
    resetSort: function() {
        $('.sort').parent()
                .removeClass('sortdesc')
                .removeClass('sortasc');
    },
    proccessErrorAdd: function($aError) {
        $product.resetFieldAdd();

        for ($error in $aError) {
            $('#' + $product.fields[$error])
                    .after($aError[$error])
                    .css('border', '1px solid red');

            if (!$aError[$error]) {
                $('#' + $product.fields[$error])
                        .css('border', '');
            }

            $('.error-message')
                    .html($('input#error_message_add').val())
                    .show()
                    .fadeOut(3000, function() {
                $(this).empty();
            });
//            setTimeout(function(){
//                $('.error-message')
//                    .hide()
//                    .empty();
//            },3000);
        }
    },
    resetFieldAdd: function() {
        $('.error-message').empty();

        for ($field in $product.fields) {
            $('#' + $product.fields[$field]).css('border', '');
            $('#' + $product.fields[$field] + '+ div.error').remove('div.error');
        }

//Reset error message of image field.
        $('#' + $product.fields.image + '~ div.error').remove('div.error');
    },
    resetUploadImage: function() {
        $('div.upload-image-product + div.error').remove('div.error');
    },
    resetUploadImgInput: function() {
        $('#form_image_product').get(0).reset();
        $('div.upload-image-product + div.error').remove('div.error');
    },
    resetFormAdd: function() {
        $('#form_add').get(0).reset();
        $product.resetFieldAdd();
        $('#product_image').val('');
        $('#product_image + img').remove('img');
        $('#product_image + br').remove('br');
        //reset error of image field.
        $('#product_image ~ .error').remove('div');
    },
    add: function() {
        tinyMCE.triggerSave();
        //Set cur_page to input hidden, use for reload page when edit.
        var $curPage = $('#current_page_product').text();
        $('input#product_cur_page').val(!$curPage ? 1 : $curPage);

        var $option = {
            type: 'post',
            url: $('#form_add').attr('action'),
            dataType: 'json',
            data: $('#form_add').serialize(),
            success: function($response, $status) {
                if ($response.result) {
                    if (!$response.data.cur_page) {
                        location.reload();

                        return;
                    }

                    //In case edit page, reload that page.
                    $('#dialog_add').dialog('close');
                    /////////////////////////////
                    $page.get($response.data.cur_page);
//                    $product.getList($response.data.cur_page);
                }
                else {
                    $product.proccessErrorAdd($response.data);
                }
            }
        };

        $.ajax($option);
    },
    uploadImage: function() {
        $('#form_image_product').ajaxForm({
            success: function($response) {
                $response = eval('(' + $response + ')');

                if ($response.result) {
                    $product.createImage($response.data);
                    $product.resetUploadImgInput();

                    return true;
                }
                //Reset.
                $product.resetUploadImage();
                $('div.upload-image-product').after($response.message);
            }
        });

        return this;
    },
    createImage: function($object) {
        if ($object == '' || $object == 'undefined') {
            return false;
        }

        //Remove image append the previous time.
        $('#product_image').siblings('img').remove('img');
        //Append new image.
        $('#product_image')
                .val($object.file_name)
                .after("<img src='" + $object.obsolute_path_new_image + "' height='100px' width='100px' alt='' /><br />");

        return true;
    },
    getList: function($offset) {
        $page.get($offset);

        return this;
    },
    getSearchObject: function() {
        return $('#form_search').serialize();
    },
    createList: function($productDataList) {
        var $data = $productDataList;
        var $body = $('#body_list');
        $body.empty();

        //Check if no post in table product.
        $('#no_row').remove();

        if (!$data) {

            $body.append('<tr id="no_row" class="no-row"><td colspan="11">' + $lang.phrases.no_product + '</td></tr>');
        }

        //Traverse list product
        for (var $i = 0; $i < $data.length; $i++) {
            var $list = '';
            var $row = $data[$i];
            var $productId = null;

            for (var $col in $row) {
                if ($col == 'id') {
                    $productId = $row[$col];
                }

                $list = this.fillData($col, $row[$col], $list);
            }

            $body.append($list);

            if ($i % 2) {
                $('#row_' + $productId).addClass('even');
            }
            else {
                $('#row_' + $productId).addClass('odd');
            }
        }
    },
    fillData: function($col, $data, $list) {
        var $tr = $('#row_product').html();
        $tr = $tr.replace(/^(<\!\-\-)|(\-\-\>)$/, '');
        if ($list) {
            $tr = $list
        }

        switch ($col) {
            case 'id':
                $tr = $tr.replace(/{product_id}/g, $data);
                break;
            case 'name':
                $tr = $tr.replace(/{product_name}/g, $data);
                break;
            case 'category':
                $tr = $tr.replace(/{product_category}/g, $data);
                break;
            case 'level':
                $tr = $tr.replace(/{product_level}/g, $data);
                break;
            case 'order':
                $tr = $tr.replace(/{product_order}/g, $data);
                break;
            case 'language':
                $tr = $tr.replace(/{language}/g, $data);
                break;
            case 'actived':
                $tr = $tr.replace(/{product_status}/g, ($data == 1) ? 'active' : 'inactive');
                break;
            case 'featured':
                $tr = $tr.replace(/{product_featured}/g, ($data == 1) ? 'featured' : 'unfeatured');
                break;
            default:
                $tr = $tr.replace(/{product_date}/g, $data);
                break;
        }

        return $tr;
    },
    deleteProducts: function() {
        var $class = $('.product-select');
        var $ids = '{';

        for (var $item in $class) {
            if ($class[$item].checked == true) {
                $ids += '"' + $item + '":"' + $class[$item].id + '",';
            }
        }

        $ids = $ids.replace(/,$/g, '') + '}';
        var $curPage = $('#current_page_product').text();
        $curPage = !$curPage ? 1 : $curPage;

        var $option = {
            type: 'post',
            url: $tut.siteUrl('product/admincp/index/delete'),
            dataType: 'json',
            data: {product_ids: $ids, cur_page: $curPage},
            success: function($response, $status) {
                if ($response.result) {
                    //Get list product of page.
                    ///////////////////////////
                    $page.get($response.data.page);
                }
            }
        };

        $tut.ajax($option);

        return this;
    },
    showDeletedItems: function() {
        var $class = $('.product-select');
        var $listDeleted = '';
        var $hasDelProduct = false;

        for (var $item in $class) {
            if ($class[$item].checked == true) {
                $hasDelProduct = true;
                $listDeleted += '<li class="deleted-product">' + $('#product_name_' + $class[$item].id).text() + '</li>';
            }
        }

        $listDeleted = '<ol>' + $listDeleted + '</ol>';
        //if no product is deleted that isn't show dialog.
        if ($hasDelProduct) {
            //Show dialog delete product.
            $dialog.confirmExt(
                    function() {
                        $product.deleteProducts();
                    },$listDeleted, 'Are you sure to delete these products?');
        }

        return this;
    },
    resetDeletedItems: function() {
        //Append to section deleted product dialog.
        $('#list_deleted_product').empty();
        return this;
    },
    getById: function($id) {
        var $option = {
            type: 'post',
            url: $tut.siteUrl('product/admincp/index/get'),
            dataType: 'json',
            data: {product_id: $id},
            success: function($response, $status) {
                if ($response.result) {
                    //populate product into edit form. and set useful.
                    $product.populate($response.data);
                }
            }
        };

        $tut.ajax($option);
        return this;
    },
    populate: function($data) {
        $('#dialog_add').dialog("open");
        //Set id to edit.
        $('#' + 'product_id').val($data.id);
        //
        $('#' + this.fields.name).val($data.name);
        $('#' + this.fields.order).val($data.order);
        $('#' + this.fields.source).val($data.source);
        $('#' + this.fields.summary).val($data.summary);
        tinyMCE.get('product_description').setContent($data.description);
        $('#' + this.fields.meta_title).val($data.meta_title);
        $('#' + this.fields.meta_keyword).val($data.meta_keyword);
        $('#' + this.fields.meta_description).val($data.meta_description);
        //Combobox
        $('#' + this.fields.level + ' option[value=' + $data.level_id + ']').prop('selected', true);
        $('#' + this.fields.language + ' option[value=' + $data.language_id + ']').prop('selected', true);
        $('#' + this.fields.meta_robot + ' option[value="' + $data.meta_robot + '"]').prop('selected', true);
        $('div#' + this.fields.status).find('input.input-radio[value=' + $data.is_actived + ']').prop('checked', true);
        $('div#' + this.fields.featured).find('input.input-radio[value=' + $data.is_featured + ']').prop('checked', true);

        //Assign for image product.
        var $image = {
            file_name: $data.image,
            obsolute_path_new_image: $tut.appUrl('static/images/product/thumb/' + $data.image)
        };

        this.createImage($image);
        //Change title from add to edit.
        $('#dialog_add').dialog('option', 'title', $lang.phrases.edit_product);
        //Change action from add to edit.
        $('#form_add').attr('action', $tut.siteUrl('product/admincp/index/edit'));

        return this;
    },
    renderDescriptionField: function() {
        // Initialize TinyMCE with and listbox
        tinyMCE.init({
            plugins: '-example', // - tells TinyMCE to skip the loading of the plugin
            mode: "exact",
            elements: 'product_description',
            theme: "advanced",
            theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,forecolor,backcolor",
            theme_advanced_buttons3: "hr,removeformat,visualaid,|,sub,sup,|,charmap",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            width: "600",
            height: "500"
        });

        return this;
    }
};
var $page = {
    action: '',
    class: 'page',
    container: '',
    content: '',
    init: function() {
        this.get(0)
                ._intEvent();
        this.container = $('#pagination');
    },
    _intEvent: function() {
        this._initEventChangePage()
                ._initEventSetView();
    },
    _initEventChangePage: function() {
        $('.' + this.class).live('click', function($event) {
            $event.preventDefault();
            //Show loader icon.
            $loader.start();
            this.action = $(this).attr('href');

            var $option = {
                type: 'post',
                url: this.action,
                dataType: 'json',
                data: $product.getSearchObject(),
                success: function($response, $status) {
                    if ($response.result) {
                        $page.create($response.data.pages)
                                .addClass(this.class);

                        $product.createList($response.data.products);
                        //Hide loader icon.
                        $loader.complete();
                    }
                }
            };

            $tut.ajax($option);

        });

        return this;
    },
    _initEventSetView: function() {
        //Choose number of element to view..
        $('#pagination_number_view').live('change', (function($event) {
            $loader.start();
            var $num_view = $(this).val();
            var $option = {
                type: 'post',
                url: $tut.siteUrl('product/admincp/index/setView'),
                dataType: 'json',
                data: {num_view: $num_view},
                success: function($response, $status) {
                    if ($response.result) {
                        $page.get(0);
                        //Hide loader icon.
                        $loader.complete();
                    }
                }
            };

            $tut.ajax($option);

        }));

        return this;
    },
    get: function($pageNum) {
        //Show loader icon.
        $loader.start();

        this.action = $tut.siteUrl('product/admincp/index/getList');

        if ($pageNum) {
            this.action += '/' + $pageNum;
        }
        else {
            this.action += '/' + 1;
        }

        var $option = {
            type: 'post',
            url: this.action,
            dataType: 'json',
            data: $product.getSearchObject(),
            success: function($response, $status) {
                if ($response.result) {
                    $page.create($response.data.pages)
                            .addClass(this.class);

                    $product.createList($response.data.products);
                    //Hide loader icon.
                    $loader.complete();
                }
            }
        };

        $tut.ajax($option);


        return this;
    },
    create: function($data) {
//        this.content = JSON.parse($data);
        this.content = $data;
        this.container.empty().append(this.content);

        return this;
    },
    addClass: function() {
        this.container.find('a').addClass(this.class);

        return this;
    }
};